package com.schoolvisitors.controller.admin;

import com.alibaba.fastjson2.JSONObject;
import com.schoolvisitors.CheckPermission;
import com.schoolvisitors.dto.AdminDto;
import com.schoolvisitors.entity.Admin;
import com.schoolvisitors.entity.Role;
import com.schoolvisitors.enums.PermissionEnum;
import com.schoolvisitors.exception.BusinessException;
import com.schoolvisitors.response.ResultBody;
import com.schoolvisitors.response.ResultCode;
import com.schoolvisitors.service.AdminService;
import com.schoolvisitors.service.RoleService;
import com.schoolvisitors.vo.AdminVo;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/admin")
public class AdminController {
    private final AdminService adminService;
    private final RoleService roleService;

    public AdminController(AdminService adminService, RoleService roleService) {
        this.adminService = adminService;
        this.roleService = roleService;
    }

    @CheckPermission(PermissionEnum.SYSTEM_ADMIN)
    @GetMapping("/getAdmins")
    public ResultBody getAdmins() {

        List<Admin> admins = adminService.getAdmins();
        List<AdminVo> adminVos = admins.stream().map(AdminVo::new).collect(Collectors.toList());

        return ResultBody.success(adminVos);
    }


    // 创建管理员接口
    @CheckPermission(PermissionEnum.SYSTEM_ADMIN)
    @PostMapping("/createAdmin")
    public ResultBody createAdmin(@RequestBody @Valid AdminDto adminDto) {
        if (adminDto.getPassword() == null){
            throw new BusinessException(ResultCode.PASSWORD_NOT_FOUND);
        }
        adminService.createAdmin(adminDto);
        return ResultBody.success();
    }

    // 更新管理员接口
    @CheckPermission(PermissionEnum.SYSTEM_ADMIN)
    @PostMapping("/updateAdmin")
    public ResultBody updateAdmin(@RequestBody @Valid AdminDto adminDto) {
        adminService.updateAdmin(adminDto);
        return ResultBody.success();
    }

    @CheckPermission(PermissionEnum.SYSTEM_ADMIN)
    @PostMapping("/deleteAdmin")
    public ResultBody removeAdmin(@RequestBody JSONObject json) {
        Long adminId = json.getLong("adminId");
        adminService.deleteAdmin(adminId);
        return ResultBody.success();
    }

}
